define(function(require,exports,module){
	var Form = require("form");
	var store = require("store");
	var activeUser = store.get("user");
	
	var aw = require("ajaxwrapper");
	var Dialog =require("dialog");
	
	var getEndGrid = require("../../../nonmemcheckout/src/component/renderEndGrid");
	var getTotalGrid = require("../../../nonmemcheckout/src/component/renderTotalGrid");
	var getSignupCharge =require("../../../nonmemcheckout/src/store/getSignupCharge");
	var total = require("../../../nonmemcheckout/src/handler/total");
	var settleData = require("../../../nonmemcheckout/src/constant/settleData");
	
	module.exports = {
			confirmClick : function(data, widget){
				
				var settelmentUnit;
				var signUpType = data.checkInImplement.nonMemGroupReserve.nonMemberGroup.signUpType.key;
				if(data.checkInImplement.dataSource.key == "VisitDoorFIT"){
					settelmentUnit = data.checkInImplement.nonMemGroupReserve.nonMemberGroup.operator.servicePoint.name;
				}else if(signUpType == "NonMember"){
					settelmentUnit = data.checkInImplement.nonMemGroupReserve.nonMemberGroup.groupUnit;
				}else{
					settelmentUnit =  data.checkInImplement.nonMemGroupReserve.nonMemberGroup.operator.servicePoint.name;
				};
				
				var confirmData = widget.get("confirmData");
				var flag = false;
				if(confirmData.length != 0){
					flag = true;
					data.content = confirmData[0].content;
					//settelmentUnit = confirmData[0].settelmentUnit;
					data.confirmDate = confirmData[0].confirmDate;
					data.confirmOperatorName = confirmData[0].confirmOperator.name;
				}
				
				var paymentMethods = [];
				for(var i = 0; i < data.paymentMethods.length; i++){
					paymentMethods[i] = data.paymentMethods[i].value;
				}
				
				
				var confirmForm = new Form({
	        		parentNode:".J-selfform",
	        		autoRender : false,
		  			model:{
						id:"roomform",
						layout : "2_1",
						defaultButton : false,
						items:[{
							name : "pkCheckOutSetlConfirm",
							type : "hidden"
						},{
							name : "version",
							type : "hidden",
							defaultValue : "0"
						},{
							name : "checkOutDeal",
							type : "hidden",
							defaultValue : data.pkCheckOutDeal
						},{
							name : "confirmOperator",
							type : "hidden",
							defaultValue : activeUser.pkUser
						},{
							name : "groupUnit",
							label : "付款单位或个人",
							readonly : true,
							defaultValue : settelmentUnit
						},{
							name : "content",
							label : "款项内容",
							validate:["required"],
							defaultValue : data.content
						},{
							name : "checkInDate",
							type : "date",
							label : "入住日期",
							readonly : true,
							defaultValue : moment(data.checkInImplement.nonMemGroupReserve.
									nonMemberGroup.checkInDate).format("YYYY-MM-DD")
						},{
							name : "checkOutDate",
							type : "date",
							label : "退房日期",
							readonly : true,
							defaultValue : moment(data.checkInImplement.nonMemGroupReserve.
									nonMemberGroup.checkOutDate).format("YYYY-MM-DD")
						},{
							name : "money",
							label : "结算金额",
							readonly : true,
							defaultValue : data.money.toFixed(2)
						},{
							name : "payment",
							label : "付款方式",
							readonly : true,
							defaultValue : paymentMethods
						},{
							name : "billing",
							label : "是否开票",
							readonly : true,
							defaultValue : data.billing ? "是" : "否"
						},{
							name : "billingDate",
							label : "开票日期",
							readonly : true,
							defaultValue : data.billingDate ? moment(data.billingDate).format("YYYY-MM-DD") : ""
						},{
	                    	name : "settelmentUnit",
	                    	label : "收款单位",
	                    	validate:["required"],
	                    	defaultValue : activeUser.servicePoint.name,
	                    	"break" : true
						},{
							name : "confirmOperatorName",
							label : "确认人",
							readonly : true,
							defaultValue : data.confirmOperatorName == "" 
								|| data.confirmOperatorName == undefined 
								? activeUser.name : data.confirmOperatorName,
						},{
							name : "confirmDate",
							label : "确认日期",
							type : "date",
							readonly : true,
							defaultValue : data.confirmDate == "" 
								? moment(new Date).format("YYYY-MM-DD") : moment(data.confirmDate).format("YYYY-MM-DD"),
						}]
		  			 }
	            });
				widget.set("confirmForm", confirmForm);
				
				if(flag){
//					confirmForm.setDisabled(true); 
				}
				
				Dialog.showComponent(confirmForm,{
					defaultButton:false,
					title: "散客结算确认",
					buttons :[{
						id:"save",
						text:"保存",
						className:"btn-primary",
						handler:function(){
							if(confirmForm.valid()){
								var FormData = confirmForm.getData();
								var data = {
										pkCheckOutSetlConfirm : FormData.pkCheckOutSetlConfirm,
										version : FormData.version,
										checkOutDeal : FormData.checkOutDeal,
										confirmOperator : FormData.confirmOperator,
										confirmDate : FormData.confirmDate,
										content : FormData.content,
										settelmentUnit : FormData.settelmentUnit,
								};
								aw.saveOrUpdate("api/checkoutsetlconfirm/saveconfirm",aw.customParam(data),function(data){
									Dialog.close();
				          			widget.get("grid").refresh();
				       			});
							};
						}
					},{
						id:"close",
						text:"取消",
						handler:function(){
							Dialog.close();
						}
					}]
				});

			},
			
			checkClick : function(data, widget){
				this.settlementClick(data, widget);
				widget.detail = true;
				widget.get("totalGrid").setDisabled(true);
				widget.get("subnav").hide(["paymentMethod","servicePoint", "status", "checkOutDate"]).show(["return","totalprint"]);
			},
			settlementClick : function(data, widget){
				getEndGrid.renderGrid(widget);
				getTotalGrid.renderEditGrid(widget);
				var endGrid = widget.get("endGrid");
				var liveDays = (moment(data.checkInImplement.nonMemGroupReserve.nonMemberGroup.checkOutDate).startOf("day").valueOf() - 
						moment(data.checkInImplement.nonMemGroupReserve.nonMemberGroup.checkInDate).startOf("day").valueOf())/1000/60/60/24;
				endGrid.setData([]);
				
				var dis = false;
				//widget.get("subnav").show(["save"]);
				if(widget.get("check")){
					//widget.get("subnav").hide(["save"]);
					dis = true;
				}
				//查询结算子表
				var pkCheckOutDeal = data.pkCheckOutDeal;
				getSignupCharge(pkCheckOutDeal,function(tdata){
					$.each(tdata,function(i,n){
						n.liveDays = parseInt(liveDays);
						n.disabled = dis;
						n.roomPersonalInfo.checkOutSettlement.sum += n.roomPersonalInfo.damagesConsumption + n.roomPersonalInfo.roomConsumption;
						n.roomPersonalInfo.checkOutSettlement.balance = n.roomPersonalInfo.checkOutSettlement.sum
						- n.roomPersonalInfo.checkOutSettlement.bedSubsidy
						- n.roomPersonalInfo.checkOutSettlement.coupon
						- n.roomPersonalInfo.checkOutSettlement.expense;
					});
					endGrid.setData(tdata);
					total.total(widget,tdata,data);
				});
				
				widget.set("pkNonMemberGroup",data.checkInImplement.nonMemGroupReserve.nonMemberGroup.pkNonMemberGroup);
				widget.set("pkCIImplement",data.checkInImplement.pkCIImplement);
				widget.toSubGrid();
				widget.get("form").setData({
					pkCheckOutDeal : data.pkCheckOutDeal,
					checkInImplement : data.checkInImplement.pkCIImplement,
					version : data.version,
					desName : data.checkInImplement.servicePoint.name,
					checkInDate : moment(data.checkInImplement.nonMemGroupReserve.nonMemberGroup.checkInDate).format("YYYY-MM-DD"),
					checkOutDate : moment(data.checkInImplement.nonMemGroupReserve.nonMemberGroup.checkOutDate).format("YYYY-MM-DD"),
					signUpNumber : data.checkInImplement.signUpNum,
					description : data.checkInImplement.nonMemGroupReserve.nonMemberGroup.description,
				});
				if(data.operator){
					widget.get("form").setValue("operator", data.operator.pkUser);
				}
				if(data.settlementDate){
					widget.get("form").setValue("settlementDate", data.settlementDate);
				}
				if(data.operator){
					widget.get("form").setValue("operator", data.operator.pkUser);
				}
				if(data.operator){
					widget.get("form").setValue("operatorName", data.operator.name);
				}
				var signUpRoomData = data.checkInImplement.nonMemGroupReserve.signUpRooms;
				
				var rtData = this.readyRoomTypeData(signUpRoomData);
				
				widget.set("forms", []);
				for(var i = 0; i < rtData.length; i++){
					this.roomDetailForm(rtData[i], widget);
				}
				for(var i=0;i<data.paymentMethods.length;i++){
					if(data.paymentMethods[i].key=="OnCredit"){
						var form = widget.get("onCreditForm")
						form.setValue("company",data.checkInImplement.company);
						form.setValue("perName",data.checkInImplement.perName);
						form.setValue("phone",data.checkInImplement.phone);
						form.setValue("onCreditMoney",data.checkInImplement.onCreditMoney);
						form.setDisabled(true);
						widget.show([".J-onCreditForm"]);
					}
				};
				
			},
			readyRoomTypeData : function(data){
				var roomTypeDatas = [];
				for(var i=0;i<data.length;i++){
					var map = {};
					var roomTypeData = {
						rtName : data[i].roomType.name,
						roomPriceDatas: []
					};
					var priceDatas = data[i].signUpRoomPrices;
					for(var j=0;j<priceDatas.length;j++){
						var roomPriceData = {
							roomPrice : priceDatas[j].roomPrice,
							checkInPrice : priceDatas[j].checkInPrice
						};
						var price = priceDatas[j].roomPrice;
						var pk = data[i].roomType.pkRoomType;
						var key = price + "_" + pk;
						if(!map[key]){
							roomPriceData.num = 0;
							map[key] = roomPriceData;
						}
						map[key].num = map[key].num + 1;
					};
					for(var k in map){
						roomTypeData.roomPriceDatas.push(map[k]);
					}
					roomTypeDatas.push(roomTypeData);
				}
				return roomTypeDatas;
			},
			roomDetailForm : function(data, widget){
				var items = [{
					name: "rtName",
		            label: "房型",
		            defaultValue : data.rtName,
		            readonly : true,
		            "break" : true
				}];
				
				var priceData = data.roomPriceDatas;
				for(var i = 0; i < priceData.length; i++){
					var roomPrice = {
						name: "roomPrice" + (i+1),
			            label: "房价" + (i+1),
			            defaultValue : priceData[i].roomPrice,
			            readonly : true
					};
					var checkInPrice = {
						name: "checkInPrice" + (i+1),
			            label: "入住价" + (i+1),
			            defaultValue : priceData[i].checkInPrice,
			            readonly : true
					};
					var num = {
						name: "num" + (i+1),
			            label: "天数" + (i+1),
			            defaultValue : priceData[i].num,
			            readonly : true
					};
					items.push(roomPrice);
					items.push(checkInPrice);
					items.push(num);
				}
				
				var aform = new Form({
	        		parentNode:".J-form",
		  			model:{
						id:"aroomform",
						layout : "3_1",
						defaultButton : false,
						items:items
		  			 }
	            });
	        	widget.set("form" + data.rtName, aform);
	        	widget.get("forms").push(aform);
			},
			settle:function(widget,ret,index,disabled){
				widget.set("cGridData",ret);
				var detailForm = widget.get("detailForm");
				var data = ret.roomPersonalInfo;
				var member = widget.member;
				
				var electric = data.checkOutSettlement.electric ? data.checkOutSettlement.electric : 0,
					food = data.checkOutSettlement.food ? data.checkOutSettlement.food : 0,
					coupon = data.checkOutSettlement.coupon ? data.checkOutSettlement.coupon :0,
					expense = data.checkOutSettlement.expense ? data.checkOutSettlement.expense:0,
					bedSubsidy = data.checkOutSettlement.bedSubsidy ?data.checkOutSettlement.bedSubsidy:0,
					room = data.checkOutSettlement.room ? data.checkOutSettlement.room :0,
					bedSubsidyUnit = data.checkOutSettlement.bedSubsidyUnit;
				
				detailForm.reset();
				detailForm.setValue("index",index);
				detailForm.setData(data.checkOutSettlement);
				detailForm.setValue("name", data.nonMemberRegister.signUpRegister.personalInfo.name);
				detailForm.setValue("idNumber", data.nonMemberRegister.signUpRegister.personalInfo.idNumber);
				detailForm.setValue("liveDays", ret.liveDays);
				detailForm.setValue("roomCode", ret.roomPersonalInfo.roomRegister.room.code);
				detailForm.setValue("roomType", ret.roomPersonalInfo.roomRegister.room.roomType.name);
				detailForm.setValue("checkInDate", widget.get("form").getValue("checkInDate"));
				detailForm.setValue("checkOutDate", widget.get("form").getValue("checkOutDate"));
				if(data.nonMemberRegister.signUpRegister.travelContract){
					detailForm.setValue("travelContract",
							data.nonMemberRegister.signUpRegister.travelContract.pkTravelContract);
					detailForm.setValue("contractNumber", data.nonMemberRegister.signUpRegister.travelContract.productRule.product.name + "-"
							+ data.nonMemberRegister.signUpRegister.travelContract.memberCertificates);
					detailForm.setValue("bedSubsidyUnit",bedSubsidyUnit);
				}
				if(bedSubsidyUnit){
					detailForm.setValue("bedSubsidyUnit",bedSubsidyUnit);
				}
				detailForm.setDisabled(true);
			
				$(".J-detailForm .J-grid-total-info").hide();
				widget.get("settleEditGridOne").setData(settleData.settleDataOne(data,widget,disabled));
				widget.get("settleEditGridTwo").setData(settleData.settleDataTwo(data,widget,disabled));
				widget.toForm();
			},
	};
})